package com.atguigu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class MyLogGatWayFalter implements Ordered, GlobalFilter {
//    自定义全局gateway 过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //例子，请求的参数必须有uname
        log.info("MyLogGatWayFalter: " + new Date());
        //获取 请求路径中 是否带有 username
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if( username  == null){
            log.info("用户名为null 非法用户");
            //给出一个未找到的响应  不被通过
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        //否则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //配置优先级   0最先
        return 0;
    }
}
